<template>
	<view class="compress">
		<canvas :style="{ width: canvasSize.width, height: canvasSize.height }" canvas-id="myCanvas" style="
        visibility: hidden;
        position: absolute;
        top: -9999px;
        left: -9999px;
      "></canvas>
	</view>
</template>

<script>
	// import { uploadImgUrl } from "@/api/selfs";
	import urlConfig from "@/request/urlConfig.js";
	import W from "../l-signature/signature";
	export default {
		data() {
			return {
				pic: "",
				canvasSize: {
					width: 0,
					height: 0,
				},
			};
		},
		methods: {
			// 压缩
			compress(params, modelThat, index) {
				let that = this;
				return new Promise(async (resolve, reject) => {
					// 等待图片信息
					let info = await this.getImageInfo(params.path)
						.then((info) => info)
						.catch((err) => err);

					if (!info) {
						reject("获取图片信息异常");
						return;
					}

					// 设置最大 & 最小 尺寸
					const maxSize = params.maxSize || 680;
					const minSize = params.minSize || 425;

					// 当前图片尺寸
					let {
						width,
						height
					} = info;

					// 非 H5 平台进行最小尺寸校验
					// // #ifndef H5
					// if (width <= minSize && height <= minSize) {
					//   resolve(params.src);
					//   return;
					// }
					// #endif
					uni.showLoading({
						title: "加载中",
					});
					// 最大尺寸计算
					if (width > maxSize || height > maxSize) {
						if (width > height) {
							height = Math.floor(height / (width / maxSize));
							width = maxSize;
						} else {
							width = Math.floor(width / (height / maxSize));
							height = maxSize;
						}
					}
					uni.showLoading({
						title: "加载中",
					});
					// console.log(width, height);
					// 设置画布尺寸
					this.$set(this, "canvasSize", {
						width: `${width}px`,
						height: `${height}px`,
					});

					// Vue.nextTick 回调在 App 有异常，则使用 setTimeout 等待DOM更新
					setTimeout(() => {
						const ctx = uni.createCanvasContext("myCanvas", this);
						ctx.clearRect(0, 0, width, height);
						ctx.drawImage(info.path, 0, 0, uni.upx2px(width), uni.upx2px(height));
						ctx.draw(false, () => {
							uni.canvasToTempFilePath({
									x: 0,
									y: 0,
									width: uni.upx2px(width),
									height: uni.upx2px(height),
									destWidth: width,
									destHeight: height,
									canvasId: "myCanvas",
									fileType: params.fileType || "png",
									quality: params.quality || 1,
									success: (res) => {
										// 在H5平台下，tempFilePath 为 base64

										let str = res.tempFilePath;
										const blob = that.parseBlob(str);
										uni.uploadFile({
											url: urlConfig.baseURL +
												'sys/file/uploadFile',
											filePath: blob,
											name: "file",
											header: {
												'User-Token': uni
													.getStorageSync('token') ||
													"",
											},
											success: function(res) {

												console.log(res,
													"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
												);
												if (res.statusCode ==
													200) {
													uni.hideLoading();
													uni.showToast({
														title: "上传成功",
														icon: "none",
														duration: 1500,
													});
													// that.formData.pic.push(JSON.parse(res.data).datas);
													console.log(params,
														"~~~~~~~~~~~~~~2222222222222"
													);
													let model = JSON.parse(
														res.data);
													// . = "";
													model.datas.file_id =
														params.uuid;

													resolve(model);

												} else {
													uni.hideLoading();
													if (index || index ===
														0) {
														let model =
															"filePicker" +
															index;
														if (typeof index ===
															"number") {
															modelThat
																.$refs[
																	model][
																	0
																]
																.clearFiles(
																	0);
														} else {
															modelThat
																.$refs[
																	model]
																.clearFiles(
																	0);
														}
													} else {
														let model =
															"filePicker";
														modelThat.$refs[
																model]
															.clearFiles(0);
													}
													uni.showToast({
														title: "图片上传失败",
														icon: "none",
														duration: 1500,
													});
												}
											},
											fail: function(err) {
												uni.hideLoading();
												uni.showToast({
													title: "上传失败",
													icon: "none",
												});
												if (index || index === 0) {
													let model =
														"filePicker" +
														index;
													if (typeof index ===
														"number") {
														modelThat.$refs[
																model][0]
															.clearFiles(0);
													} else {
														modelThat.$refs[
																model]
															.clearFiles(0);
													}
												} else {
													modelThat.$refs
														.filePicker
														.clearFiles(0);
												}
											},
										});
									},
									fail: (err) => {
										reject(null);
										uni.hideLoading();
									},
								},

							);
						});
					}, 300);
				});
			},

			parseBlob(str) {
				var arr = str.split(",");

				var mime = arr[0].match(/:(.*?);/)[1];

				var bstr = atob(arr[1]);

				var n = bstr.length;

				var u8arr = new Uint8Array(n);

				for (var i = 0; i < n; i++) {
					u8arr[i] = bstr.charCodeAt(i);
				}

				var url = URL || webkitURL;

				return url.createObjectURL(new Blob([u8arr], {
					type: mime
				}));
			},

			// 获取图片信息
			getImageInfo(src) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src,
						success: (info) => {
							resolve(info);
						},
						fail: () => {
							reject(null);
						},
					});
				});
			},
			// 批量压缩
			batchCompress(params) {
				// index:进度，done:成功，fail:失败
				let [index, done, fail] = [0, 0, 0];
				// 压缩完成的路径集合
				let paths = [];
				// 批量压缩方法
				let batch = () => {
					return new Promise((resolve, reject) => {
						// 开始
						let start = async () => {
							params.progress &&
								params.progress({
									done,
									fail,
									count: params.batchSrc.length,
								});
							// 等待图片压缩方法返回
							let path = await next();
							if (path) {
								done++;
								paths.push(path);
							} else {
								fail++;
							}

							index++;
							// 压缩完成
							if (index >= params.batchSrc.length) {
								resolve(true);
							} else {
								start();
							}
						};
						start();
					});
				};
				// 依次调用压缩方法
				let next = () => {
					return this.compress({
						src: params.batchSrc[index],
						maxSize: params.maxSize,
						fileType: params.fileType,
						quality: params.quality,
						minSize: params.minSize,
					});
				};

				// 全部压缩完成后调用
				return new Promise(async (resolve, reject) => {
					// 批量压缩方法回调
					let res = await batch();
					if (res) {
						resolve(paths);
					} else {
						reject(null);
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
</style>